<?php


namespace App\Http\Controllers;

use App\Internals\UserInternal;
use App\Models\Lesson;
use App\Models\LessonSection;
use FoxLib\Services\UrlParamsService;

class LessonController extends Controller
{
    /*
     * @api get /course-api/lesson/share 课程分享页数据
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function share()
    {
        $this->validate($this->request, [
            'refer' => 'required|string'
        ]);
        $ref = $this->request->input('refer');
        $refInfo = UrlParamsService::decode($ref);

        $userInfo = UserInternal::getByUserId($refInfo['userId']);

        /** @var Lesson $lessonObj */
        $lessonObj = Lesson::find($refInfo['lessonId']);
        $metadata = LessonSection::ofShare($refInfo['lessonId'])->value('metadata');
        $metadata = json_decode($metadata, true);
        $cover = $lessonObj->cover()->value('uri');
        if ($cover) {
            $cover .= '?x-oss-process=style/lesson_cover';
        }
        $thumbCover = $lessonObj->thumbCover()->value('uri');
        if ($thumbCover) {
            $thumbCover .= '?x-oss-process=style/lesson_thumb_cover';
        }
        $result = [
            'user' => [
                'nickname' => $userInfo['nickname']
            ],
            'lesson' => [
                'name' => $lessonObj->getName(),
                'audio' => $lessonObj->audio()->value('uri'),
                'thumbCover' => $thumbCover,
                'cover' => $cover,
            ],
            'pages' => array_slice($metadata['pages'], 0, 5)
        ];
        return $this->sendSuccessJson($result);
    }
}
